package SIM_report;

#Copyright 2006 - 2010 Bernard van de Koppel
#This file is part of Sipman
#Sipman is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#Sipman is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with Sipman.  If not, see <http://www.gnu.org/licenses/>.
#
require Exporter;
use CGI qw(param);
use SIM_settings;
use SIM_base;
use SIM_cgiSettings;
use SIM_cgi;
use SIM_nodeInfo;
use SIM_updateInfo;
use SIM_rrd;
use strict;

our @ISA 	= ("Exporter");
our @EXPORT	= qw( 
                      @reportNames reportHeader processReccord printReportActions searchIndex
                      %reportedInfo;
                     );
our @VERSION	= 0.01;			# version number

# include variabeles to be used over the various modules here.
#
#
#my $userLevel = $ENV{'USERLEVEL'};
# ------------------- base reccordinfo --------------------------------------
our @reportReccords = ();
our %reportedInfo = ();
our %updatedInfo = ();
our @reportNames = ();
my $reportName;
my @dbDirs = ( 'SIMdataConfDir', 'SIMmainConfigDir' );
foreach my $entry (@dbDirs) {
  push(@reportReccords, "$entry $SIMparam{$entry}/deviceReports");
  if ( -f "$SIMparam{$entry}/deviceReports" ) {
    open( INFO, "$SIMparam{$entry}/deviceReports" ) || die ("Oops, could not read sms info from $entry.");
    while (my $reccord = <INFO>) {
      my ( $type, $rest ) = split(';', $reccord, 2);
      if ( $type eq "report" ) {
        ( $reportName, $rest ) = split(';', $rest);
        push(@reportNames, $reportName);
      } elsif (( $type eq "ip" ) or ( $type eq "fmac" ) or ( $type eq "mac" ) or ( $type eq "hw" ) or ( $type eq "dev" ) or ( $type eq "var" ) or ( $type eq "section" )) {
        my $newRec = "$reportName;$type;$rest";
        push(@reportReccords, $newRec);
      }
    }
    close INFO;
    last
  }
}
# ------------------- exportable subs -------------------------
sub printReportCacheActions {
  my $tool =  "@_[0]";
  my $action =  "@_[1]";
  my $cacheFile = "@_[2]";
  my $report = "@_[3]";
  my $sep = "Report:";
  foreach my $entry (@reportNames) {
    printEntry2("$entry","Display report $entry", "$tool+$action+$cacheFile+$report", "$tool+$action+$cacheFile+$entry", "", "line", "$sep", "");
    $sep = "|";
  }
}

sub searchIndex {
  # search an build cachefile, or use cache file.
  my $tool = "@_[0]";
  my $action = "@_[1]";
  my $cachefile = "@_[2]";
  my $reportName = "@_[3]";
# my $reportAction = "@_[3]";
  my $createCache;
  my $dispAction = "listEntry";
  if ( $reportName eq "" ) {
    $reportName = $SIMparam{'SIMdefaultIpListReport'};
  }
  printDebug(1, "searchIndex: tool=$tool, action=$action, cachefile=$cachefile, reportName=$reportName.");
  my @found;
  if ( "$action" eq "searchCache" ) {
    my $searchString = param('searchstring');
    $createCache = "yes";
    $action = "listCache";
    print("Searching for $searchString.<HR>");
    # search case insensitive.
    @found = ` grep -i \"$searchString\" $SIMparam{'SIMipSearchIndex'} `;
    open( OUT, ">$SIMparam{'SIMtmpDir'}/$cachefile" ) || die "Problems creating cachfile $cachefile.";
  } else {
    if ( $action eq "updCache" ) {
      $dispAction = "dispEntry";
      print("<FORM method=post Action=$httpScriptName?$tool+$action+$cachefile+$reportName>
               <INPUT TYPE=hidden NAME=form VALUE=yes>");
    }
    open( IN, "$SIMparam{'SIMtmpDir'}/$cachefile" );
    @found = <IN>;
    close(IN);
    # test and if neccessary update.
    my $formInput = param('form');
    if ( "$formInput" eq "yes" ) {
      foreach my $entry (@found) {
        my ( $ipAddr, $rest ) = split(' ', $entry);
#       &processReccord( $ipAddr, "updEntry", "line", $reportName, "dummy" );
        &processReccord( $ipAddr, "updEntry", "line", $reportName );
      }
    }
  }
  print("<BR>");
  if ( $action ne "updCache" ) {
    printEntry2("Update","Update this list", "$tool+$action+$cachefile+$reportName", "$tool+updCache+$cachefile+$reportName", "", "line", " . ", "");
  } else {
    printEntry2("List","List this list", "$tool+$action+$cachefile+$reportName", "$tool+listCache+$cachefile+$reportName", "", "line", " . ", "");
  }
  printReportCacheActions("mon", $action, $cachefile, $reportName);
  printEntry2("Csv","report csv", "$tool+$action+$cachefile+$reportName", "$tool+generateCsv+$cachefile+$reportName", "", "line", " Export: ", "");
  # file name for the csv reporting.
  my $random = int( rand( 10000000 ));
  my $csvName = "$random/$cachefile-$reportName.csv";
  my $csvFile = "$SIMparam{'SIMgraphDir'}/$csvName";
  my $testNum = 1;
  if ( $found[0] ne "" ) {
    if ( $action eq "generateCsv" ) {
      if ( $reportName eq "ipList" ) {
        # ipList report would generate an empty report, replace it with an valid report which looks like it.
        $reportName = $SIMparam{'SIMipListCsvReplacement'};
      }
      &testMkDir("$SIMparam{'SIMgraphDir'}/$random");
      print("<HR><PRE>");
      &reportHeader( $reportName, "csv", "$csvFile");
      print("<HR>Generating: ");
    } else {
      print("<TABLE>");
      &reportHeader( $reportName );
    }
    foreach my $entry (@found) {
      my ( $ipAddr, $rest ) = split(' ', $entry);
#     printNodeLine($ipAddr);
      if ( $action eq "generateCsv" ) {
        $testNum++;
        if ( $testNum > 1000 ) {
          print(" $ipAddr ");
          $testNum = 0;
        }
        &processReccord( $ipAddr, "listEntry", "csv", $reportName, $csvFile );
      } else {
        my $ipDir = getIpDir($ipAddr);
        my $nodeType = catFileLine("$ipDir/nodetype.txt");
        &processReccord( $ipAddr, $dispAction, "line", $reportName );
        if ( "$createCache" eq "yes" ) {
          print OUT ("$ipAddr\n");
        }
      }
    }
    if ( $action eq "generateCsv" ) {
      print("</PRE><HR>");
      print("<A HREF=/graphs/$csvName>Csv file</A>");
    } else {
      reportHeader( $reportName );
      print("</TABLE>");
      &dispColorTable;
    }
    if ( "$createCache" eq "yes" ) {
      close(OUT);
    } elsif ( $action eq "updCache" ) {
      print("<INPUT TYPE=submit VALUE=\"Update definitions\" /></FORM>");
    }
  } else {
    print("No info found for $reportName");
  }
}


sub printReportActions {
  my $action =  "@_[0]";
  my $subnet =  "@_[1]";
  my $report = "@_[2]";
  my $sep = "Report:";
  foreach my $entry (@reportNames) {
    printEntry2("$entry","Display report $entry", "$action+$subnet+$report", "$action+$subnet+$entry", "", "line", "$sep", "");
    $sep = "|";
  }
}

sub calcMinAvgMax {
  my $responseInfo = "@_[0]";
  my @respArray = split(' ', $responseInfo);
  my ( $sum, $avg, $results );
  my $num = 0;
  my $min = $respArray[0];
  my $max = $respArray[0];
  foreach my $entry (@respArray) {
    if ( $min > $entry ) {
      $min = $entry;
    }
    if ( $max < $entry ) {
      $max = $entry;
    }
    $sum = $sum + $entry;
    $num++;
  }
  if ( $num eq 0 ) {
    $results = "<CENTER>NA";
  } else {
    $avg = $sum / $num;
    $avg = sprintf("%.2f", $avg);
    $results = "$min / $avg / $max";
  }
  return $results;
}

sub reportHeader {
  my $report = "@_[0]";
  my $reportType = "@_[1]";
  my $reportFile = "@_[2]";
  my $outLine;
  if ( $reportType ne "csv" ) {
    print("<TR BGCOLOR=#DDDDDD VALIGN=bottom>");
  }
  foreach my $entry (@reportReccords) {
    my ( $repName, $source, $access, $recName, $recDescr, $typeInfo, $descr ) = split(';', $entry);
    my ( $readLevel, $writeLevel ) = split('\:', $access);
    if ( $userLevel < $readLevel ) {
      # do nothing, no access to this data
    } elsif ( $repName eq $report ) {
      if ( $recName eq "nodeInfo" ) {
        if ( $reportType eq "csv" ) {
          $outLine = "${outLine}Net;ipAddr;macAddr;type;type2;status;dnsName;hostName;snmpOid;int;port;";
        } else {
          print("<TD></TD>
            <TD>Net</TD>
            <TD>Ip addres</TD>
            <TD>Mac addres</TD>
            <TD COLSPAN=2>Type</TD>
            <TD>Status</TD>
            <TD>Dns name</TD>
            <TD>Host name</TD>
            <TD>Snmp Oid name</TD>
            <TD>Int</TD>
            <TD>Port</TD>
              ");
        }
      } elsif ( $recDescr ne "" ) {
        if ( $reportType eq "csv" ) {
          my ( $recType, $recOpt ) = split('\:', $typeInfo);
          if ( $recType eq "var" ) {
            $source = "var";
          }
          $outLine = "$outLine\"$source:$recName\";";
        } else {
          print("<TD>$recDescr</TD>");
        }
      }
    }
  }
  if ( $reportType ne "csv" ) {
    print("</TR>");
  } else {
    print("remoteUser: $remoteUser, userLevel: $userLevel. ");
    print("Creating header: report=$report, reportFile=$reportFile, reportReccords=" . @reportReccords . ".\n");
    printFileLine($reportFile,"append","$outLine\"var:test\"\r\n");
  }
}

sub getMacAddr {
  my $ipAddr = "@_[0]";
  my $ipDir = getIpDir( $ipAddr );
  my $macAddr;
  if ( -f "$ipDir/dhcpmacaddr.txt" ) {
    $macAddr = catFileLine("$ipDir/dhcpmacaddr.txt");
  } elsif ( -f "$ipDir/snmpmac.txt" ) {
    $macAddr = catFileLine("$ipDir/snmpmac.txt");
  } elsif ( -f "$ipDir/arpmac.txt" ) {
    $macAddr = catFileLine("$ipDir/arpmac.txt");
  } else {
    $macAddr = "none";
  }
  return $macAddr;
}

sub processReccord {
  my $ipAddr = "@_[0]";
  my $action = "@_[1]";
  my $displayType = "@_[2]";
  my $report = "@_[3]";
  my $outFile = "@_[4]";
  my ( $sourceDir, $outReccord, $section );
  my $ipDir = getIpDir($ipAddr);
  my $nodeType = catFileLine("$ipDir/nodetype.txt");
  if ( $report eq "" ) {
    $report = "default";
  }
  my $hwName = catFileLine("$ipDir/hwName");
  my $hwDir;
  if ( $hwName ne "" ) {
    $hwDir = "$SIMparam{'SIMhardwareInfoDir'}/$hwName";
  } else {
    $hwDir = "";
  }
  my $firstMac = catFileLine("$ipDir/firstmac.txt");
  my $firstMacDir = "$SIMparam{'SIMmacDatab'}/$firstMac";
  my $macAddr = getMacAddr( $ipAddr );
  my $macDir = "$SIMparam{'SIMmacDatab'}/$macAddr";
  my $devDir;
  if ( -f "$ipDir/vendor" ) {
    $devDir = getDevDir( $ipAddr );
  }
# print("ipAddr=$ipAddr, action=$action, displayType=$displayType, report=$report, nodeType=$nodeType, outFile=$outFile.\n");

  # actions: line, colum, update
# if (( $action eq "listEntry" ) or ( $action eq "dispEntry" ) or ( $action eq "updEntry" )) {
  if ( $displayType eq "line" ) {
    print("<TR BGCOLOR=$typeColor{$nodeType}>\n");
#   print("<TD>action=$action, report=$report $reportReccords</TD>");
  }
  foreach my $entry (@reportReccords) {
    my ( $outData );
    my ( $repName, $source, $access, $recName, $recDescr, $typeInfo, $descr ) = split(';', $entry);
#   print("$repName");
    my ( $readLevel, $writeLevel ) = split('\:', $access);
    if ( $repName eq $report ) {
      my ( $dispType, $dispOpt ) = split('\:', $typeInfo);
      if ( $source eq "ip" ) {
        $sourceDir = $ipDir;
      } elsif ( $source eq "hw" ) {
        $sourceDir = $hwDir;
      } elsif ( $source eq "fmac" ) {
        $sourceDir = $firstMacDir;
      } elsif ( $source eq "mac" ) {
        $sourceDir = $macDir;
      } elsif ( $source eq "dev" ) {
        $sourceDir = $devDir;
      } elsif ( $source eq "section" ) {
        $section = $access;
      }
      my $sourceFile = "$sourceDir/$recName";
      # for table entries start the row and display the reccord name.
#     Section moved to hide rows if not used in the table view     
#     if (( $displayType eq "table" ) and ( $source ne "section" ) and ( $userLevel >= $readLevel )) {
#       print("<TR><TD><B>$section</B></TD><TD>$recDescr</TD>");
#       $section = "";
#     }
      if ( $userLevel < $readLevel ) {
        printDebug( 1, "Sorry no access.");
        # skipping this reccord
      } elsif (( $dispType eq "read" ) or ( $dispType eq "text" )  or ( $dispType eq "select" )) {
        my $sourceInfo = catFileLine($sourceFile);
        if (( $action eq "listEntry" ) or ( $userLevel < $writeLevel ) or (( $dispType eq "read" ) and ( $action eq "dispEntry" ))) {
          if ( $displayType eq "csv" ) {
            $outReccord = "$outReccord\"$sourceInfo\",";
          } else {
            if ( $sourceInfo eq "" ){
              $outData = "<TD></TD>";;
            } elsif ( $dispOpt eq "mac" ) {
              my $ouiMac = substr($sourceInfo, 0, 8);
              my $vendor = catFileLine("$SIMparam{'SIMmacOuiDir'}/$ouiMac/vendor");
              if ( $vendor eq "" ) {
                $vendor = "undefined";
              }
              $outData = "<TD>$sourceInfo (<A HREF=$httpScriptName?mon+updateOui+$ouiMac>$vendor</A>)</TD>";
              my $vendorInfo = &displayOui($sourceInfo);
              $outData = "<TD>$sourceInfo $vendorInfo</TD>";
            } elsif ( $dispOpt eq "syslogInfo" ) {
              my ( $logEntry, $logDevName ) = split(' ', $sourceInfo);
              $outData = "<TD><A HREF=$httpScriptName?extra+syslog+list+$logEntry+$logDevName>$sourceInfo</A></TD>";
            } elsif ( $dispOpt eq "oidInfo" ) {
              $outData = "<TD><A HREF=$httpScriptName?config2+dispoidinfo+$ipAddr+summary>$sourceInfo</A></TD>";
            } else {
              #$outData = "<TD>$sourceInfo $dispOpt</TD>";
              $outData = "<TD>$sourceInfo</TD>";
            }
          }
        } elsif ( $dispType eq "select" ) {
          if ( $recName eq "nodetype.txt" ) {
            if ( $action eq "dispEntry" ) {
              $outData = "<TD><SELECT NAME=nodeType-$ipAddr SIZE=1><OPTION VALUE=\"$nodeType\">$nodeType</OPTION>";
              foreach my $key ( keys %typeColor ) {
                if ( $dispOpt eq "detail" ) {
                  $outData = "$outData<OPTION VALUE=$key>$key = $typeDescr{$key}</OPTION>";
                } else {
                  $outData = "$outData<OPTION VALUE=$key>$key</OPTION>";
                }
              }
              $outData = "$outData</SELECT></TD>";
            } elsif ( $action eq "updEntry" ) {
              my $newNodeType  = param("nodeType-$ipAddr");
              if ( $nodeType ne $newNodeType ) {
                setNodeType( $ipAddr, $remoteUser, $newNodeType );
              }
            }
          } elsif ( $recName eq "managementtype.txt" ) {
            my $manType = catFileLine("$ipDir/managementtype.txt");
            if ( $action eq "dispEntry" ) {
              $outData = "<TD><SELECT NAME=manType-$ipAddr SIZE=1><OPTION VALUE=\"$manType\">$manType</OPTION>";
              while ( my ($key, $value) = each(%manAbrev) ) {
                $outData = "$outData<OPTION VALUE=$key>$key</OPTION>";
              }
              $outData = "$outData</SELECT></TD>";
            } elsif ( $action eq "updEntry" ) {
              # there is still a bug in this part, need to work on this later
              my $newManType  = param("manType-$ipAddr");
              if ( $manType ne $newManType ) {
                setManType( $ipAddr, $remoteUser, $newManType );
              }
            }
          } elsif ( $recName eq "sipmanrectype.txt" ) {
            my $recType  = catFileLine("$ipDir/sipmanrectype.txt");
            if ( $action eq "dispEntry" ) {
              $outData = "<TD><SELECT NAME=recType-$ipAddr SIZE=1><OPTION VALUE=\"$recType\">$recType</OPTION>";
              while ( my ($key, $value) = each(%recColor) ) {
                $outData = "$outData<OPTION VALUE=$key>$key</OPTION>";
              }
              $outData = "$outData</SELECT></TD>
                <INPUT TYPE=hidden NAME=\"org-recType-$ipAddr\" VALUE=\"$recType\">";
            } elsif ( $action eq "updEntry" ) {
              my $newRecType  = param("recType-$ipAddr");
              if ( $recType ne $newRecType ) {
                setRecType( $ipAddr, $remoteUser, $newRecType );
                if ( $newRecType eq "DEL" ) {
                  # if an ip reccord is removed, dont process the rest.
                  last;
                }
              }
            }
          }
        } elsif ( $dispType eq "text" ) {
          my $currVal = catFileLine($sourceFile);
          # update part.
          if ( $action eq "dispEntry" ) {
            if ( $reportedInfo{$sourceFile} ne "" ) {
              $outData = "<TD>$currVal</TD>";
            } elsif (( ! -d $sourceDir ) and ( $source ne "ip" )) {
              $outData = "<TD ALIGN=center>NA</TD>";
            } else {
              $outData = "<TD><INPUT TYPE=text NAME=\"$recName-$ipAddr\" VALUE=\"$currVal\" SIZE=$dispOpt></TD>
                              <INPUT TYPE=hidden NAME=\"org-$recName-$ipAddr\" VALUE=\"$currVal\">";
            }
            $reportedInfo{$sourceFile} = "$source:$recName $currVal";
          } elsif ( $action eq "updEntry" ) {
            if ( $updatedInfo{$sourceFile} eq "" ) {
              my $orgVal = param("org-$recName-$ipAddr");
              my $newVal = param("$recName-$ipAddr");
              chomp $newVal;
              if (( $currVal ne $newVal ) and ( $orgVal ne $newVal )) {
                updField( $ipAddr, $remoteUser, $recDescr, $sourceFile, $newVal );
              }
            }
            $updatedInfo{$sourceFile} = "$source:$recName $currVal";
          }
        }
      } elsif ( $dispType eq "var" ) {
        if ( $recName eq "hwName" ) {
          $sourceFile = "$ipDir/hwName";
          my $currVal = catFileLine($sourceFile);
          # check hw ip field ( to repair should things get out of sync )
          my $longIp = longIp($ipAddr);
          my $ipHwFile = "$SIMparam{'SIMhardwareInfoDir'}/$currVal/ipInt-$longIp";
          if (( $currVal ne "" ) and ( ! -f "$ipHwFile" )) {
            testMkDir("$SIMparam{'SIMhardwareInfoDir'}/$currVal");
            printFileLine($ipHwFile, "quiet", $ipAddr);
          }
          if (( $action eq "dispEntry" ) and ( $userLevel >= $writeLevel )) {
            $outData = "<TD><INPUT TYPE=text NAME=\"$recName-$ipAddr\" VALUE=\"$currVal\" SIZE=15></TD>";
          } elsif ( $action eq "updEntry" ) {
            my $formName  = param("$recName-$ipAddr");
#           $formName = testDnsName($formName);
#           my ( $hostPart, $domain ) = split('\.', $formName);
#           if ( $currVal ne $hostPart ) {
#             my $hwDir = "$SIMparam{'SIMhardwareInfoDir'}/$hostPart";
#             if ( ! -d $hwDir ) {
#               system(" mkdir -p $hwDir ");
#             }
#             &updField( $ipAddr, $remoteUser, $recDescr, $sourceFile, $hostPart );
#           }
            &updHwName( $ipAddr, $remoteUser, $formName);
          } elsif ( $userLevel >= $readLevel ) {
            # else read the field if allowed
            if ( $displayType eq "csv" ) {
              $outReccord = "$outReccord\"$currVal\",";
            } else {
              $outData = "<TD>$currVal</TD>";
            }
          }
        } elsif ( $recName eq "switchInfo" ) {
          my $macAddr = &getMacAddr($ipAddr);
          my $info;
          if ( $userLevel >= $readLevel ) {
            if ( $displayType eq "csv" ) {
              $info = getSwitchPort($macAddr, "csv");
            } else {
              $info = getSwitchPort($macAddr, "link");
            }
            if ( $displayType eq "csv" ) {
              $outReccord = "$outReccord\"$info\",";
            } else {
              $outData = "<TD>$info</TD>";
            }
          }
        } elsif ( $recName eq "snmpoid" ) {
          $sourceFile = "$ipDir/snmpoid.txt";
          my $currVal = catFileLine($sourceFile);
          my ( $type, $oid ) = split(' ', $currVal);
          if (( $action ne "updEntry" ) and ( $userLevel >= $readLevel )) {
            if ( $displayType eq "csv" ) {
              $outReccord = "$outReccord\"$type, $oid\",";
            } else {
             $outData = "<TD>$type, $oid</TD>";
            }
          }
        } elsif ( $recName eq "dnsname.txt" ) {
          $sourceFile = "$ipDir/dnsname.txt";
          my $currVal = catFileLine($sourceFile);
          my ( $type, $hostName, $domainName ) = split(' ', $currVal);
          if (( $action ne "updEntry" ) and ( $userLevel >= $readLevel )) {
            if ( $displayType eq "csv" ) {
              $outReccord = "$outReccord\"$hostName.$domainName $type\",";
            } else {
              $outData = "<TD>$hostName.$domainName ( type = $type )</TD>";
            }
          }
        } elsif (( $action eq "listEntry" ) or ( $action eq "dispEntry" )) {
          if ( $recName eq "ipAddr" ) {
            if ( $displayType eq "csv" ) {
#             print("ipAddr=$ipAddr, ");
              $outReccord = "$outReccord\"$ipAddr\",";
            } else {
              $outData = "<TD>$ipAddr</TD>";
            }
          } elsif ( $recName eq "externalInfo" ) {
            my $lineData;
            my @extInfo = ` grep -h \" $ipAddr \" $SIMparam{'SIMfixedInfoDir'}/* `; 
            if ( $extInfo[0] eq "" ) {
              $outReccord = "$outReccord\"\",";
            } else {
              if ( $displayType eq "csv" ) {
                $outReccord = "$outReccord\"";
              }
              foreach my $line (@extInfo) {
                chomp $line;
                my ( $info, $testIpAddr, $description ) = split(' ', $line, 3);
                if ( $ipAddr eq $testIpAddr ) {
                  if ( $displayType eq "csv" ) {
                    $lineData = "$lineData$info: $description. ";
                  } else {
                    $outData = "$outData<TR><TD>$info:</TD><TD>$description</TD></TR>";
                  }
                }
              }
              if ( $displayType ne "csv" ) {
                $outData = "$outData</TABLE></TD>";
              }
            }
            if ( $displayType eq "csv" ) {
              $outReccord = "$outReccord$lineData\",";
            } elsif ( $outData ne "" ) {
              # wrap the out data in its own table if data is found.
              $outData = "<TD><TABLE>$outData</TABLE></TD>";
            } else {
              # produce an empty string if no data is found (will not be displayed).
              $outData = "<TD></TD>";
            }
          } elsif ( $recName eq "pollStatus" ) {
            if ( $displayType eq "csv" ) {
              my $pollStatus = catFileLine("$ipDir/pollstatus.txt");
              $outReccord = "$outReccord\"$pollStatus\",";
            } else {
              my $nodeStatus = dispNodeStatus( $ipAddr, "return" );
              $outData = "$nodeStatus";
            }
          } elsif ( $recName eq "responseInfo" ) {
            my $responseInfo = catFileLine("$ipDir/responseInfo");
            my $results = calcMinAvgMax($responseInfo);
            if ( $displayType eq "csv" ) {
              $outReccord = "$outReccord\"$results\",";
            } else {
              if ( -f "$ipDir/icmpResponseInfo-$ipAddr.rrd" ) {
                $outData = displayRrdGraph("$ipDir", "icmpResponseInfo-$ipAddr", "$dispOpt", 
                          "Ping response info for $ipAddr.", "rtt m/sec", "", "Response time", "640", "AVERAGE");
                $outData = "<TD>$outData</TD>";
              } else {
                $outData = "<TD>$results</TD>";
              }
            }
          } elsif ( $recName eq "NumPorts" ) {
            if ( -f "$firstMacDir/ipnetnum.txt" ) {
              my $ipNum = catFileLine("$firstMacDir/ipnetnum.txt");
              my $l2Num = catFileLine("$firstMacDir/intnum.txt");
              $outData = "<TD>Ip: $ipNum / Int: $l2Num</TD>";
              if ( $displayType eq "csv" ) {
                $outReccord = "$outReccord\"Ip: $ipNum / Int: $l2Num\",";
              } 
            } else {
              if ( $displayType eq "csv" ) {
                $outReccord = "$outReccord\"NA\",";
              } else {
                $outData = "<TD>NA</TD>";
              }
            }
          } elsif ( $recName eq "hostName" ) {
            if ( $displayType eq "csv" ) {
              my $hostName = dispHostName( $ipAddr, "data" );
              $outReccord = "$outReccord\"$hostName\",";
            } elsif ( $dispOpt eq "isSwitch" ) {
              my $hostName = dispHostName( $ipAddr, "data" );
              my $shortName = &shortHostname($hostName);
              if ( -f "$SIMparam{'SIMswitchDevices'}/$shortName/interface-info" ) {
                $outData = "<TD><A HREF=$httpScriptName?switch2+displaySwitch+$shortName>$hostName</TD>";
              } else {
                $outData = "<TD>$hostName</TD>";
              }
            } else {
              my $hostName = dispHostName( $ipAddr, "return" );
              $outData = "$hostName";
            }
          } elsif ( $recName eq "nodeInfo" ) {
            my $nodeLine = printNodeLine( $ipAddr, "return" );
            $outData = "$nodeLine";
          } elsif ( $recName eq "netInfo" ) {
            my ( $info1, $gateway );
            if ( -f "$ipDir/network" ) {
              my $network = catFileLine("$ipDir/network");
              my $longNet = longIp($network);
              open(IN, "$SIMparam{'SIMsubnetDir'}/net-$longNet");
              my @lines = <IN>;
              close IN;
              foreach my $entry (@lines) {
                my ( $type, $rest ) = split(' ', $entry, 2);
                if ( $type eq "NETWORK:" ) {
                  my ( $network, $netMask, $broadcast ) = split(' ',$rest);
                  $info1 = "net: $network, mask: $netMask, broad: $broadcast ";
                } elsif ( $type eq "OPTION:" ) {
                  my ( $optType, $value ) = split(' ', $rest);
                  if ( $optType eq "routers" ) {
                    $gateway = "gw: $value";
                  }
                }
              }
            }
            if ( $displayType eq "csv" ) {
              $outReccord = "$outReccord\"$info1 $gateway\",";
            } else {
              $outData = "<TD>$info1$gateway</TD>";
            }
          } elsif ( $recName eq "netName" ) {
            my $netName = &getNetName( $ipAddr, $dispOpt, $displayType );
            if ( $displayType eq "csv" ) {
              $outReccord = "$outReccord\"$netName\",";
            } else {
              $outData = "<TD>$netName</TD>";
            }
          }
        }
      }
      if (( $source ne "section" ) and ( $userLevel >= $readLevel )) {
        if ( $displayType eq "line" ) {
          print("$outData\n");
        } elsif (( $displayType eq "table" ) and ( $outData ne "<TD></TD>" )) {
          my $sectionColor = "#FEFEFE";;
          if ( $section ne "" ) {
            $sectionColor = "#EEEEEE";
          } 
          print("<TR BGCOLOR=#EEEEEE><TD BGCOLOR=$sectionColor>$section</TD><TD>$recDescr</TD>$outData<TD><IMG SRC=/sipman3/gifs/comment.gif TITLE=\"$descr\" ></IMG></TD></TR>\n");
          $section = "";
        }
      }
    }
  }
# printDebug( 0, "displayType=$displayType, outReccord=$outReccord.");
  if ( $displayType eq "line" ) {
    print("</TR>\n");
  } elsif ( $displayType eq "csv" ) {
    # convert to make this file adapt to Microsoft csv format.
    $outReccord = "$outReccord\"testValue\"";
    $outReccord =~ s/;/:/g;
    $outReccord =~ s// /g;
    $outReccord =~ s/\",\"/\";\"/g;
    printFileLine($outFile, "append", "$outReccord;\r\n");
  }
# my $ipDir  = getIpDir($ipAddr);
}

1;
